import Vue from 'vue';

Vue.directive('elastic', function(ele, opt) {
    var obj = opt.value ? opt.value : {};
    //初始化数据
    var maxY = 0;
    var minY = obj.minY ? obj.minY : -667;
    var startY = 0,
        changeY = 0,
        moveY = 0;
    var elPosition = 0;
    var bufferY = obj.bufferY ? obj.bufferY : 80;
    //var ele = this.el;
    ele.addEventListener('touchstart', function(e) {
        startY = e.touches[0].clientY;
        //获取当前弹簧的高度
        //console.log(window.screen.height);
        //592(px)=window.screen.height(667:当前iphone6的总高度)-1.5rem(75px:头部+底部)
        var clcY = 592 - ele.offsetHeight;
        minY = clcY;
    });
    ele.addEventListener("touchmove", function(e) {
        e.preventDefault();
        moveY = e.touches[0].clientY;
        changeY = moveY - startY;
        var nowY = changeY + elPosition;
        if (nowY > minY - bufferY && nowY < maxY + bufferY) {
            ele.style.transition = "none";
            ele.style.transform = "translateY(" + nowY + "px)";
            //获取位置信息
            var str = ele.style.transform;
            str = str.slice(str.indexOf('(')).replace(/\(|px\)/g, "");
            //console.log({ x: 0, y: +str });
        }
        if (nowY >= bufferY) {
            Event.$emit('isLoading', 1);
        }

    });
    ele.addEventListener("touchend", function() {
        elPosition += changeY;
        if (elPosition > maxY) elPosition = maxY;
        if (elPosition < minY) elPosition = minY;
        ele.style.transition = "all 3s ease";
        ele.style.transform = "translateY(" + elPosition + "px)";
        startY = 0;
        changeY = 0;
        moveY = 0;
        if (elPosition >= 0) {
            Event.$emit('isLoading', 0);
        }
    });
});